/**
 *     This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *   
 *  ----------------------------------------------------------------------   
 *  This Android 'port' is part of original idea/project:
 *  http://code.google.com/p/arithmetic-game/
 * 
 *  Yet none of this code re-uses Qt-code itself introduced by
 *  original arithmetic-game SW.
 * 
 *  @author teppo.eeva (project contact)
 *  @author santeriv (initial 'port' in Android)
 * 
 */
package com.myopenid.santeriv.arithgame;

import java.util.Random;
import com.myopenid.santeriv.arithgame.R;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener, OnKeyListener, OnTouchListener {

	private static final int TIMER_INTERVAL = 1000;
	private boolean m_timerToBeResumed;
	private int m_expectedResult;
	private int m_score;
	private MyCount m_timerCount;
	private long m_timeLeft;
	
	TextView m_countDownTimer;
	
	/**
	 * Helper utility by Nathan Artz 
	 * @see http://dewful.com/?p=3
	 */
	public class MyCount extends CountDownTimer{
		public MyCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}
		@Override
		public void onFinish() {
			m_countDownTimer.setText("done!");
		}
		@Override
		public void onTick(long millisUntilFinished) {
			m_countDownTimer.setText("Time Left: " + millisUntilFinished/TIMER_INTERVAL);
			m_timeLeft = millisUntilFinished;
		}
	}
	public enum Difficulty
	{
		LEVEL_1,
		LEVEL_2,
		LEVEL_3
	}

	@Override
	protected void onPause() {
		super.onPause();
		stopTimer();
	}

	@Override
	protected void onResume() {
		super.onResume();
		startTimer();
	}

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        EditText answer = (EditText)findViewById(R.id.Answer);
        answer.setOnClickListener(this);
        answer.setOnKeyListener(this);
        answer.setOnTouchListener(this);
        createRiddle(Difficulty.LEVEL_1);
        this.m_score=0;
        this.m_timerToBeResumed = false;
    	this.m_countDownTimer = (TextView)findViewById(R.id.timer);
    	//5000 is the starting number (in milliseconds)
    	//1000 is the number to count down each time (in milliseconds)
    	this.m_timerCount = new MyCount(30000,TIMER_INTERVAL);
    	this.m_timeLeft = 0;
    }

	private void createRiddle(Difficulty level) {
		EditText problem = (EditText)findViewById(R.id.Problem);
        EditText answer = (EditText)findViewById(R.id.Answer);
        answer.setText("");
        int number1,number2;
        Character operands[]={'+','-','x'};
        Character operand='+';
        Random randomizer = new Random();
        switch(level)
        {
        case LEVEL_2:
            number1 = randomizer.nextInt(20);
            number2 = randomizer.nextInt(20);
            operand = operands[randomizer.nextInt(3)];
        	break;
        case LEVEL_3:	
            number1 = randomizer.nextInt(100);
            number2 = randomizer.nextInt(100);
            operand = operands[randomizer.nextInt(3)];        	
        	break;
        case LEVEL_1:
        default:
            number1 = randomizer.nextInt(20);
            number2 = randomizer.nextInt(20);
            operand = operands[randomizer.nextInt(2)];
        	break;
        }
        problem.setText(number1+" "+operand+" "+number2);
        if(operand=='+')
        {
        	this.m_expectedResult=number1+number2;
        }
        else if(operand=='-')
        {
        	this.m_expectedResult=number1-number2;
        }
        else if(operand=='x')
        {
        	this.m_expectedResult=number1*number2;
        }
	}
	@Override
	public void onClick(View aView){
		if (m_timeLeft == 0)
		{//created first time waiting for user input to start timer
			startTimer();			
		}
	}
	@Override
	public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
		EditText answer = (EditText)arg0;
		if(!(answer.getText().equals("-")) && (answer.getText().length()>0)
		)
		{
			switch(arg2.getKeyCode())
			{
			case KeyEvent.KEYCODE_ENTER:
			case KeyEvent.KEYCODE_CALL:
				int answerValue=Integer.valueOf(answer.getText().toString()).intValue();
				if(this.m_expectedResult==answerValue)
				{
					this.m_score = this.m_score + 1;
					TextView score = (TextView)findViewById(R.id.ScorePoints);
					score.setText(Integer.toString(m_score)); 
					prepareNewRiddle();
				}
				else
				{//penalty and new riddle
					if(this.m_timeLeft / TIMER_INTERVAL != 0)
					{
						prepareNewRiddle();
						stopTimer();
						this.m_timeLeft = this.m_timeLeft - 3000;
						startTimer();
					}
					else
					{//Game Ended
						//TODO: Save High Scores
						answer.setFocusable(false);
						answer.setClickable(false);
						hideAnswerEditText();
					}
				}//else - penalty and new riddle
				break;
			default:
				//no handling for other keys
				break;
			}
		}//if - answer is valid
		return false;
	}

	private void hideAnswerEditText() {
		EditText answer = (EditText)findViewById(R.id.Answer);
		answer.setFilters(new InputFilter[] { new InputFilter() {
			@Override
			public CharSequence filter(CharSequence arg0, int arg1, int arg2,
					Spanned arg3, int arg4, int arg5) {
				return arg0.length() < 1 ? arg3.subSequence(arg4, arg5) : "";
			}
		} });
	}

	private void prepareNewRiddle() {
		if(this.m_score > 1)
		{
			if(this.m_score == 2)
			{
				showDifficultyLevel(Difficulty.LEVEL_2);				
			}
			createRiddle(Difficulty.LEVEL_2);
			if(this.m_score > 2) 
			{
				if(this.m_score == 3)
				{
					showDifficultyLevel(Difficulty.LEVEL_3);				
				}
				createRiddle(Difficulty.LEVEL_3);
			}
		}
		else
		{//Easiest level 1
			showDifficultyLevel(Difficulty.LEVEL_1);
			createRiddle(Difficulty.LEVEL_1);
		}
	}
	private void showDifficultyLevel(Difficulty toDifficultyLevel) {
		if(toDifficultyLevel == Difficulty.LEVEL_2)
		{
			//TODO: replace RatingBar with ICONS
		RatingBar levelBar = (RatingBar)findViewById(R.id.LevelBar);	
		levelBar.setNumStars(2);
		}
		else if(toDifficultyLevel == Difficulty.LEVEL_3)
		{
		RatingBar levelBar = (RatingBar)findViewById(R.id.LevelBar);				
		levelBar.setNumStars(3);
		}
	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		if (this.m_timeLeft == 0)
		{//created first time waiting for user input to start timer
			startTimer();			
		}
		return false;
	}
	private void startTimer() {
		if(this.m_timerToBeResumed)
		{
			this.m_timerCount = new MyCount(this.m_timeLeft, TIMER_INTERVAL);
			this.m_timerToBeResumed = false;
		}
		this.m_timerCount.start();
	}
	private void stopTimer() {
		this.m_timerCount.cancel();
		this.m_timerToBeResumed = true;
	}

}